#include "evm_module.h"
#include <unistd.h>

//timer.setTimeout(id, timeout);
static evm_val_t evm_module_timer_setTimeout(evm_t *e, evm_val_t *p, int argc, evm_val_t *v)
{
    if(argc!=2)
        return EVM_VAL_UNDEFINED;

    if(!evm_is_number(v) || !evm_is_number(v+1))
        return EVM_VAL_UNDEFINED;

    int id = evm_2_integer(v);
    int timeout = evm_2_integer(v+1);

    evm_event_msg_t *msg = evm_module_msg_create();
    msg->event = "timeout";
    msg->id = id;
//    msg->param1 = timeout;
    evm_timer_t *timer = evm_module_timer_getInstance();
    if(timer == NULL)
        return ec_err;

    timer->start(id, msg);

    return EVM_VAL_UNDEFINED;
}

static evm_val_t evm_module_timer_setInterval(evm_t *e, evm_val_t *p, int argc, evm_val_t *v)
{
    if(argc!=2)
        return EVM_VAL_UNDEFINED;

    if(!evm_is_number(v) || !evm_is_number(v+1))
        return EVM_VAL_UNDEFINED;

    int id = evm_2_integer(v);
    int timeout = evm_2_integer(v+1);

    evm_event_msg_t *msg = evm_module_msg_create();
    msg->event = "interval";
    msg->id = id;
//    msg->param1 = timeout;
    evm_timer_t *timer = evm_module_timer_getInstance();
    if(timer == NULL)
        return ec_err;
    timer->start(id, msg);

    return EVM_VAL_UNDEFINED;
}

static evm_val_t evm_module_timer_close(evm_t *e, evm_val_t *p, int argc, evm_val_t *v)
{
    if(argc!=1)
        return EVM_VAL_UNDEFINED;

    if(!evm_is_number(v))
        return EVM_VAL_UNDEFINED;

    int id = evm_2_integer(v);

    evm_timer_t *timer = evm_module_timer_getInstance();
    if(timer == NULL)
        return ec_err;
    timer->stop(id);
    return EVM_VAL_UNDEFINED;
}

evm_err_t evm_module_timer(evm_t *e) {
    if(evm_module_timer_init()!=0)
        return ec_memory;

    evm_cffi_t funcs[] = {
        {NULL, 0, NULL}
    };

    evm_builtin_t builtin[] = {
        {"setTimeout", evm_mk_native((intptr_t)evm_module_timer_setTimeout)},
        {"setInterval", evm_mk_native((intptr_t)evm_module_timer_setInterval)},
        {"close", evm_mk_native((intptr_t)evm_module_timer_close)},
        {NULL, EVM_VAL_UNDEFINED}
    };
    evm_module_effi_create(e, "@native.timer", funcs , builtin);
    return e->err;
}

